package cc.wfu.infrastructure.persistent.repository;

import cc.wfu.domain.auth.model.entity.AuthCodeEntity;
import cc.wfu.domain.auth.repository.IAuthRepository;
import cc.wfu.infrastructure.persistent.redis.IRedisService;
import cc.wfu.types.common.RandomCodeUtil;
import cc.wfu.types.common.RedisConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @Author: jia-qiang ljq1024.cc
 * @desc: 用户权限仓储
 * @Date: 2024-05-16-12:38
 */
@Slf4j
@Repository
public class AuthRepository implements IAuthRepository {

    @Resource
    private IRedisService redisService;


    /**
     * 生成验证码
     * @param mail 邮箱
     */
    @Override
    public String generateCode(String mail) {
        // 1. 拼接 key
        String cacheKey = RedisConstants.USER_SERVICE_LOGIN_CODE + mail;
        // 2. 生成验证码
        String code = RandomCodeUtil.generateComplexCode(6);
        // 3. 缓存
        redisService.setValue(cacheKey, code, 5L, TimeUnit.MINUTES);
        return code;
    }

    /**
     * 验证验证码
     * @param authCodeEntity 参数： mail,code
     */
    @Override
    public boolean checkCode(AuthCodeEntity authCodeEntity) {
        String cacheKey = RedisConstants.USER_SERVICE_LOGIN_CODE + authCodeEntity.getEmail();
        String cacheCode = redisService.getValue(cacheKey);
        if (authCodeEntity.getCode().equalsIgnoreCase(cacheCode)) {
            redisService.remove(cacheKey);
            return true;
        }
        return false;
    }
}
